package org.footito.android.connexion;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class ConnexionApiHandler extends DefaultHandler {

	private static final String TAG_LOGIN = "login";
	private static final String TAG_SUCCESS = "success";
	private static final String TAG_USERNAME = "username";
	private static final String TAG_USERID = "userid";

	private boolean isIn_login = false;
	private boolean isIn_success = false;
	private boolean isIn_username = false;
	private boolean isIn_userid = false;

	private int state = 0;
	private String username = "";
	private long id = -1;
	private StringBuilder stringbuilder;

	public ConnexionApiHandler() {
		stringbuilder = new StringBuilder();
	}

	@Override
	public void characters(char[] ch, int start, int length) throws SAXException {
		stringbuilder.append(new String(ch, start, length));
	}

	@Override
	public void endElement(String uri, String localName, String qName) throws SAXException {
		if (TAG_LOGIN.equals(localName)) {
			isIn_login = false;
		} else if (TAG_SUCCESS.equals(localName)) {
			isIn_success = false;
			state = Integer.parseInt(stringbuilder.toString());
		} else if (TAG_USERNAME.equals(localName)) {
			isIn_username = false;
			username = stringbuilder.toString();
		} else if (TAG_USERID.equals(localName)) {
			isIn_userid = false;
			id = Long.parseLong(stringbuilder.toString());
		}
	}

	public long getId() {
		return id;
	}

	public int getState() {
		return state;
	}
	
	public String getUsername() {
		return username;
	}

	@Override
	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
		if (TAG_LOGIN.equals(localName)) {
			isIn_login = true;
		} else if (TAG_SUCCESS.equals(localName)) {
			isIn_success = true;
			stringbuilder.setLength(0);
		} else if (TAG_USERNAME.equals(localName)) {
			isIn_username = true;
			stringbuilder.setLength(0);
		} else if (TAG_USERID.equals(localName)) {
			isIn_userid = true;
			stringbuilder.setLength(0);
		}
	}
}
